﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Eqwww.Code;
using Microsoft.Extensions.Caching.Memory;

namespace Eqwww.Config
{
    public class AppConfigProvider:IAppConfigProvider
    {
        private IConfiguration _configuration;
        private string _basePath;

        public AppConfigProvider(IWebHostEnvironment env)
        {
            var basePath = env.WebRootPath + "/configs/";
            _basePath = basePath;
            var builder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appconfig.json", optional: false, reloadOnChange: true);
            _configuration = builder.Build();
        }

        public AppConfig Load()
        {
            var config = _configuration.Get<AppConfig>();
            return config;
        }

        public void Save(AppConfig config)
        {
            Eqwww.Code.FileHelper.CreateFile(_basePath + "appconfig.json", config.ToJson());
        }
    }
}
